package com.hyt.it.ogt.ykcj.common.enums.zs;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Date;

/**
 * @Description: 证书有效期类型：-1-永久, 1-半年，2-一年，3-两年，4-三年，5-五年，6-十年
 * @Author: STARF
 * @CreateDate: 2022/06/24 15:08
 **/
@Getter
@AllArgsConstructor
public enum CertificateValidityType {

    PERMANENT(-1, "永久", 99, DateField.YEAR),
    HALF_A_YEAR(1, "半年", 6, DateField.MONTH),
    A_YEAR(2, "一年", 1, DateField.YEAR),
    TWO_YEARS(3, "两年", 2, DateField.YEAR),
    THREE_YEARS(4, "三年", 3, DateField.YEAR),
    FIVE_YEARS(5, "五年", 5, DateField.YEAR),
    TEN_YEARS(6, "十年", 10, DateField.YEAR),
    ;

    private final static String DEFAULT_DATE = "2099";

    private final Integer code;
    private final String desc;
    //  偏移量，正数为向后偏移，负数为向前偏移
    private final Integer offset;
    // 偏移的粒度大小（小时、天、月等
    private final DateField dateField;

    public static CertificateValidityType getByCode(Integer code) {
        for (CertificateValidityType enums : values()) {
            if (enums.getCode().equals(code)) {
                return enums;
            }
        }
        return PERMANENT;
    }

    /**
     * 日期根据code进行偏移
     *
     * @param date
     * @param code
     * @return
     */
    public static Date offsetDate(Date date, Integer code) {
        CertificateValidityType validityType = getByCode(code);
        if (validityType.equals(CertificateValidityType.PERMANENT)) {
            DateTime dateTime = DateUtil.parse(DEFAULT_DATE, DatePattern.NORM_YEAR_PATTERN);
            return DateUtil.beginOfDay(DateUtil.endOfYear(dateTime));
        }
        return DateUtil.offset(date, validityType.getDateField(), validityType.getOffset());
    }
}
